<template>
  <div class="product-detail-container" v-loading="loading">
    <div class="back-button">
      <el-button @click="$router.push('/')">
        <el-icon><ArrowLeft /></el-icon>
        返回列表
      </el-button>
    </div>

    <el-card v-if="product">
      <template #header>
        <div class="card-header">
          <h2>{{ product.name }}</h2>
          <div class="price">¥ {{ product.price?.toFixed(2) }}</div>
        </div>
      </template>

      <div class="product-info">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="商品ID">{{ product.id }}</el-descriptions-item>
          <el-descriptions-item label="分类ID">{{ product.cid }}</el-descriptions-item>
        </el-descriptions>

        <div class="action-buttons">
          <el-button type="primary" @click="handleEdit">编辑商品</el-button>
        </div>
      </div>
    </el-card>

    <el-empty v-else description="未找到商品信息"></el-empty>

    <!-- 编辑商品对话框 -->
    <el-dialog title="编辑商品" v-model="dialogVisible" width="500px">
      <el-form :model="productForm" :rules="productRules" ref="productFormRef" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="productForm.name" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="productForm.price" :precision="2" :min="0" />
        </el-form-item>
        <el-form-item label="分类ID" prop="cid">
          <el-input-number v-model="productForm.cid" :min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { getProductById, updateProduct, type Product } from '../api/product'

const route = useRoute()
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const productFormRef = ref()

const product = ref<Product | null>(null)
const productForm = reactive<Product>({
  name: '',
  price: 0,
  cid: 1,
})

const productRules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  cid: [{ required: true, message: '请选择分类', trigger: 'change' }],
}

onMounted(async () => {
  const id = Number(route.params.id)
  if (id) {
    fetchProductDetail(id)
  }
})

const fetchProductDetail = async (id: number) => {
  loading.value = true
  try {
    const res = await getProductById(id)
    if (res.data) {
      product.value = res.data
    } else {
      ElMessage.warning('未找到商品信息')
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
  } finally {
    loading.value = false
  }
}

const handleEdit = () => {
  if (product.value) {
    // 复制数据到表单
    Object.assign(productForm, product.value)
    dialogVisible.value = true
  }
}

const submitForm = async () => {
  if (!productFormRef.value) return

  await productFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        await updateProduct(productForm)
        ElMessage.success('更新成功')
        dialogVisible.value = false

        // 直接重新获取最新数据
        if (productForm.id) {
          fetchProductDetail(productForm.id)
        }
      } catch (error) {
        console.error('更新失败:', error)
        ElMessage.error('更新失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}
</script>

<style scoped>
.product-detail-container {
  padding: 20px;
}

.back-button {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
}

.product-info {
  margin-top: 20px;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
